package cn.airfei.aircore.core.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author: air
 * @create: 2020-03-18 10:55
 */
public class HttpServletRequestUtil {

    /**
     * 获取ip
     *
     * @return
     */
    public static String getIp() {
        HttpServletRequest request = request();
        String remoteAddr = "";
        if (request != null) {
            remoteAddr = request().getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        return remoteAddr;
    }

    /**
     * 返回当前请求 HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest request() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = requestAttributes.getRequest();
        }
        return request;
    }

    /**
     * 获取客户端浏览器版本信息
     *
     * @return
     */
    public static String getUserAgentWithHeader() {
        if (request() == null) {
            return null;
        }
        return request().getHeader("User-Agent");
    }

    /**
     * 获取头部token信息
     *
     * @return
     */
    public static String getAuthorizationWithHeader() {
        if (request() == null) {
            return null;
        }
        return request().getHeader("Authorization");
    }


}
